from django import db

from tppt.lib import utils
from tppt.lib import actions
from tppt.lib.actions.url import get_action_url

class HumanizeContext(object):
	default_values={
				'use_html': False,
				'max_length': -1,
				'max_list_length': 2,
				'entity': None
				}
	def __init__(self, data=None, **kwargs):
		values=HumanizeContext.default_values.copy()
		if data:
			values.update(data)
		values.update(kwargs)
		
		values['restricted_length']=values['max_length']>-1
		
		for key in values:
			setattr(self, key, values[key])
			
		self.values=values


	

def humanize_datetime_property(prop, value, context=HumanizeContext()):
	return value.strftime('%Y-%m-%d %H:%M:%S')
	
def humanize_reference_property(prop, value, context=HumanizeContext()):
	if value==None:
		return "#none"
	return utils.humanize_reference(value, context)

def humanize_list_property(prop, value, context=HumanizeContext()):
	if value==None:
		return "#none"
	if len(value)==0:
		return '[]'
	if not hasattr(prop, '_target'):
		if len(value)==1:
			inner=str(value[0])
		else:
			inner=reduce(lambda x, y: ("%s, %s" % (x, y)),  value)
		inner=utils.human_trunc(inner, context.max_length)
		return "[%s]" % inner
	
	target=prop._target
	eval_item=lambda x: utils.humanize_reference(x,  model=target, context=context)
	reduce_fn=lambda a, b: "%s%s, " % (a,  eval_item(b))
	
	items=value
	if context.max_list_length>=0:
		shown_items=items[0:context.max_list_length]
	else:
		shown_items=items
	items_str=reduce(reduce_fn,  shown_items[:-1],  '')
	items_str+=eval_item(shown_items[-1])
	
	if len(shown_items)<len(items):
		items_str+=', ...';
	if context.entity and context.use_html:
		from tppt.lib.model.restrictor import ListRestrictor
		restrictor=ListRestrictor(target.entities(), context.entity, prop)
		url=get_action_url('index', restrictor.get_restricted_entity_set())
		items_str+=" <a href='%s'>(all)</a>" % url;
	
	return "[%s]" % items_str 

def humanize_property(prop, value, context=HumanizeContext()):
	if value==None:
		return "#none"
	if context.restricted_length:
		value=utils.human_trunc(value, context.max_length)
	return value;


#db.Property.get_caption=lambda prop: prop.verbose_name or utils.camelcase_to_words(prop.name)
#db.Property.humanize=humanize_property
#db.ReferenceProperty.humanize=humanize_reference_property
#db.ListProperty.humanize=humanize_list_property
#db.DateTimeProperty.humanize=humanize_datetime_property
